/*
 * @lc app=leetcode.cn id=2130 lang=typescript
 *
 * [2130] 链表最大孪生和
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function pairSum(head: ListNode | null): number {
  let p = head;
  let q = head;
  // 找到中间节点，p为后半段第一个结点
  // 快慢指针
  while (q !== null) {
    p = p.next;
    q = q.next.next;
  }

  let ans = Number.MIN_SAFE_INTEGER;
  // 利用递归回溯的特性，计算孪生和
  const getValue = (p: ListNode | null): void => {
    if (p === null) {
      return;
    }
    getValue(p.next);
    ans = Math.max(ans, p.val + head.val);
    head = head.next;
  };

  getValue(p);

  return ans;
}
// @lc code=end
